/*
 * @Description: wcy
 * @Author: cy2020
 * @Date: 2022-02-25 09:05:33
 * @LastEditTime: 2022-02-25 19:44:54
 */

const deviceClient = require("./devices");
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
const connectUrl = 'http://localhost:8080/api/emb/upLoadFile';
const axios = require("axios")
const FormData = require("form-data")
const { log, getAuthInfo, getKits, RandomLatitudeGenerator, RandomLongitudeGenerator} = require('../../.vscode/src/utils');

function getMd5(fileNmae){
    const buffer = fs.readFileSync(path.join(__dirname, fileNmae));
    const hash = crypto.createHash('md5');
    hash.update(buffer, 'utf8');
    const md5 = hash.digest('hex');
    return md5;
}
/**
 * 推送实验数1000
 * 据
 * topic格式为
 */
function publish() {
    var randomNum = Math.floor(Math.random() * 5);
    const data = require('../data/channeldata' + randomNum+ '.json');
    // 创建文件
    let myData = {...data}
    myData.latitude = RandomLatitudeGenerator();
    myData.longitude = RandomLongitudeGenerator();
    myData.kitNo = getKits();
    const opt = {
        flag: 'w', // a：追加写入；w：覆盖写入
    }
    fs.writeFileSync(path.join(__dirname, 'channeldata.json'),  JSON.stringify(myData), opt, (err) => {
    if (err) {
        console.error(err)
    }
    })
    // log.info(JSON.stringify(data))
    const form = new FormData();
    const time = "1731312182921";
    const nonceStr = "zhangsan";
    form.append("sign", "0")
    form.append("nonceStr", nonceStr)
    form.append('files', fs.createReadStream(path.join(__dirname, './capture.jpg')));//'file'是服务器接受的key
    form.append('files', fs.createReadStream(path.join(__dirname, './channeldata.json')));//'file'是服务器接受的key
    form.append("time", time);
    form.append("pid", data.deviceNo)
    form.append("productId", "CarryOnP1000Q")
    form.append("params", JSON.stringify({"fileMd5List":[
        {"filemd5":getMd5("capture.jpg"),"filename":"capture.jpg"},
        {"filemd5":getMd5("channeldata.json"),"filename":"channeldata.json"},
    ]}))
    axios({
        method: "POST",
        url: connectUrl,
        data: form,
        headers: {
                "Content-Type": "multipart/form-data"
        }
    }).then(res => {
        if (res.status == 200) {
            console.log("suc","请求成功：")
            console.log(res.data)
            if (res.data == null) {
                console.log("suc","业务错误：")
            }
        }else{
            console.error("err", "请求失败：--------");
        }
    }).catch(res=>{
        console.error(res.data)
    })
}
publish();
  
setInterval(function(){
  //开始 多请求
 publish();
}, 10000)